package dao;

import model.MsgType;
import util.*;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.List;

/**
 * author 黄锦涛
 * 修订 by 兰彦真
 */
public class MsgTypesManager implements MsgTypesManagement {
//---------------------------------------------------------------------------------------------------

    private static List<MsgType> getResultList(List<Object[]> list)
    {
        MsgType msgTyp = null;

        List<MsgType> result = new ResultList<>();

        for(Object[] row : list)
        {
            msgTyp = new MsgType();

            msgTyp.setMsgtyp_id((Long) row[0]);
            msgTyp.setMsgtyp_name((String) row[1]);
            msgTyp.setMsgtyp_descript((String) row[2]);

            result.add(msgTyp);
        }
        return result;
    }

    @Override
    public List<MsgType> findAll(int pageSize, int page) {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            List<Object[]> list = conn.query("select * from t_mtypes limit ?, ?", (page - 1) * pageSize, pageSize);
            JDBCFactory.returnBack(conn);

            return getResultList(list);
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public MsgType findByName(String name) {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            List<Object[]> list = conn.query("select * from t_mtypes where msgtyp_name = ?", name);
            JDBCFactory.returnBack(conn);

            return getResultList(list).get(0);
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public MsgType findByID(Long id) {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            List<Object[]> list = conn.query("select * from t_mtypes where msgtyp_id = ?", id);
            JDBCFactory.returnBack(conn);

            return getResultList(list).get(0);
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    //----------------------------------------------------------------------------------------------------

    @Override
    public Long newNotice(MsgType msgType) {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            Long gKey = ((BigInteger) conn.updateForGeneratedKey("insert into t_mtypes values(null,?,?)", msgType.getMsgtyp_name(), msgType.getMsgtyp_descript())).longValue();
            JDBCFactory.returnBack(conn);
            return gKey;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    /**
     * 删除消息类别和其下属所有消息
     * @param msgType 消息的类别
     * @return 删除的消息条数
     */
    @Override
    public int deleteNotice(MsgType msgType) {
        if(msgType == null  ||  msgType.getMsgtyp_id() == null && Common.isStringEmpty(msgType.getMsgtyp_name())) return 0;

        Long msgTypeID = null;

        try {
            //从连接池获取连接
            JDBCConnection conn = JDBCFactory.takeJDBC();
            //开启事务
            conn.start();

            //若不知道消息类别的id，按消息类别名称获取id
            if ((msgTypeID = msgType.getMsgtyp_id()) == null) {
                List<Object[]> tmp = conn.query("select msgtyp_id from t_mtypes where msgtyp_name = ?", msgType.getMsgtyp_name());

                //未找到该名称的消息类型
                if (tmp.size() == 0) {
                    //回滚事务
                    conn.rollback();
                    JDBCFactory.returnBack(conn);
                    return 0;
                }
                msgTypeID = (Long) JDBCConnection.getGeneratedKey(tmp);
            }

            //获得该类型下所有消息的id
            List<Object[]> msgIds = conn.query("select msg_id from t_messages where msgtyp_id = ?", msgTypeID);

            //删除该类型下的所有消息
            conn.preparedUpdateBatch("delete from t_msgsends where msg_id = ?");
            for (Object[] row : msgIds) conn.addUpdateBatch(row[0]);
            conn.preparedUpdateBatch("delete from t_messages where msg_id = ?");
            for (Object[] row : msgIds) conn.addUpdateBatch(row[0]);
            conn.submitUpdateBatch();

            //删除消息类别
            conn.update("delete from t_mtypes where msgtyp_id = ?", msgTypeID);

            //提交事务
            conn.commit();
            //归还连接到连接池
            JDBCFactory.returnBack(conn);
            return msgIds.size();
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return 0;
        }
    }

    @Override
    public boolean updateNotice(MsgType msgType, MsgType desti) {

        if(msgType == null  ||  desti == null  || Common.isStringEmpty(msgType.getMsgtyp_name()) && msgType.getMsgtyp_id() == null
                || Common.isStringEmpty(desti.getMsgtyp_name()) && Common.isStringEmpty(desti.getMsgtyp_descript())
        ) return false;

        boolean firstArg = true;
        String sql_condition = null;
        StringBuilder sql_args = new StringBuilder();
        ArgsList<Object> args = new ArgsList<>();

        if(!Common.isStringEmpty(desti.getMsgtyp_name()))
        {
            if(!firstArg) sql_args.append(',');
            sql_args.append(" msgtyp_name = ?");
            args.add(desti.getMsgtyp_name());
            firstArg = false;
        }

        if(!Common.isStringEmpty(desti.getMsgtyp_descript()))
        {
            if(!firstArg) sql_args.append(',');
            sql_args.append(" msgtyp_descript = ?");
            args.add(desti.getMsgtyp_descript());
            firstArg = false;
        }

        //若不知道消息类别的id，按消息类别名称获取id
        if(msgType.getMsgtyp_id() != null) {
            sql_condition = " where msgtyp_id = ?";
            args.add(msgType.getMsgtyp_id());
        } else {
            sql_condition = " where msgtyp_id = ?";
            args.add(msgType.getMsgtyp_name());
        }

        try {
            //更新记录
            JDBCConnection conn = JDBCFactory.takeJDBC();
            int msgTypeID = conn.update(args, "update t_mtypes set" + sql_args.toString() + sql_condition);
            JDBCFactory.returnBack(conn);

            return msgTypeID == 1;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return false;
        }
    }

    //测试
    public static void main(String[] args) throws ClassNotFoundException {
        /*测试添加
        Class.forName(JDBCFactory.class.getName());
        Scanner sc=new Scanner(System.in);

        MsgTypesManagement notice= new MsgTypesManager();
        MsgType mtype = new MsgType();

        System.out.println("请输入添加的消息类别名");
        mtype.setMsgtyp_name(sc.next());
        System.out.println("请输入添加的消息类别描述");
        mtype.setMsgtyp_descript(sc.next());

        System.out.println(notice.newNotice(mtype));
        */

        /*测试查询 by 黄锦涛
        //加载连接池
        Class.forName(JDBCFactory.class.getName());
        System.out.println("请输入查看的消息类别名");
        Scanner sc=new Scanner(System.in);

        MsgTypesManagement notice= new MsgTypesManager();
        String msgtyp_name =sc.next();

        System.out.println(notice.findByName(msgtyp_name));
        */

        /*测试修改
        Class.forName(JDBCFactory.class.getName());
        System.out.println("请输入查看的消息类别名");
        Scanner sc=new Scanner(System.in);

        MsgTypesManagement notice= new MsgTypesManager();

        MsgType msgtyp = new MsgType();
        MsgType msgtyp2 = new MsgType();

        msgtyp.setMsgtyp_name(sc.next());
        msgtyp2.setMsgtyp_name(sc.next());
        msgtyp2.setMsgtyp_descript(sc.next());

        System.out.println(notice.updateNotice(msgtyp, msgtyp2));
        */

        /*测试删除
        Class.forName(JDBCFactory.class.getName());
        System.out.println("请输入查看的消息类别名");
        Scanner sc=new Scanner(System.in);

        MsgTypesManagement notice= new MsgTypesManager();

        MsgType msgtyp = new MsgType();

        msgtyp.setMsgtyp_name(sc.next());

        System.out.println(notice.deleteNotice(msgtyp));
        */
    }
}
